<template>
  <el-dialog
    v-model="visible"
    :title="dish?.name || '菜品详情'"
    width="60%"
    destroy-on-close
  >
    <div class="dish-detail">
      <div class="dish-info-section">
        <div class="dish-image">
          <el-image
            :src="dish?.image_url || '/default-dish.jpg'"
            fit="cover"
          />
        </div>
        <div class="dish-info">
          <h2 class="dish-name">{{ dish?.name }}</h2>
          <div class="dish-tags">
            <el-tag
              v-for="tag in parseTags(dish?.tags)"
              :key="tag"
              :type="getTagType(tag)"
              size="small"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
          <div class="dish-price">¥{{ dish?.price }}</div>
          <div class="dish-description">{{ dish?.description }}</div>
          <el-button 
            type="primary"
            :disabled="dish?.Stock <= 0"
            @click="addToCart(dish)"
          >
            {{ dish?.Stock > 0 ? '加入购物车' : '已售罄' }}
          </el-button>
        </div>
      </div>

      <div class="reviews-section">
        <div class="reviews-header">
          <h3>用户评价</h3>
          <div class="reviews-summary" v-if="reviews?.length > 0">
            <span class="review-count">{{ reviews.length }}条评价</span>
            <el-rate
              :model-value="Number(averageRating)"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </div>
        </div>

        <div v-if="reviews?.length > 0" class="reviews-list">
          <div v-for="review in reviews" :key="review.id" class="review-item">
            <div class="review-header">
              <div class="reviewer-info">
                <span class="reviewer">{{ review.username }}</span>
                <el-rate
                  :model-value="Number(review.rating)"
                  disabled
                  text-color="#ff9900"
                />
              </div>
              <span class="review-time">{{ formatDate(review.created_at) }}</span>
            </div>
            <div class="review-content">{{ review.content }}</div>
            <div v-if="review.images?.length > 0" class="review-images">
              <el-image
                v-for="(image, index) in review.images"
                :key="index"
                :src="image"
                :preview-src-list="review.images"
                fit="cover"
                class="review-image"
              />
            </div>
            <div v-if="review.reply" class="review-reply">
              <span class="reply-label">商家回复：</span>
              <span class="reply-content">{{ review.reply }}</span>
            </div>
          </div>
        </div>
        <div v-else class="no-reviews">
          暂无评价
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'

const props = defineProps({
  modelValue: Boolean,
  dish: Object
})

const emit = defineEmits(['update:modelValue', 'add-to-cart'])

const store = useStore()
const visible = ref(false)
const reviews = ref([])

watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal && props.dish) {
    loadReviews()
  }
})

watch(() => visible.value, (newVal) => {
  emit('update:modelValue', newVal)
})

const loadReviews = async () => {
  if (!props.dish?.ID) return
  
  try {
    const response = await fetch(`http://localhost:8080/api/reviews/dish/${props.dish.ID}`, {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    console.log("reviews", data)
    if (response.ok) {
      reviews.value = data.reviews
    }
  } catch (error) {
    console.error('Load reviews error:', error)
    ElMessage.error('加载评价失败')
  }
}

const parseTags = (tags: string | string[]) => {
  if (typeof tags === 'string') {
    try {
      return JSON.parse(tags)
    } catch {
      return []
    }
  }
  return tags || []
}

const getTagType = (tag: string) => {
  const tagTypeMap: Record<string, string> = {
    '辣': 'danger',
    '特辣': 'danger',
    '中辣': 'warning',
    '微辣': 'warning',
    '酸': 'warning',
    '甜': 'success',
    '咸': 'info',
    '招牌': 'primary',
    '新品': ''
  }
  return tagTypeMap[tag] || ''
}

const averageRating = computed(() => {
  if (!reviews.value?.length) return 0
  const total = reviews.value.reduce((sum, review) => sum + Number(review.rating), 0)
  return (total / reviews.value.length).toFixed(1)
})

const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const addToCart = (dish: any) => {
  emit('add-to-cart', dish)
}
</script>

<style scoped>
.dish-detail {
  padding: 20px;
}

.dish-info-section {
  display: flex;
  gap: 24px;
  margin-bottom: 32px;
}

.dish-image {
  width: 300px;
  height: 300px;
  overflow: hidden;
  border-radius: 8px;
}

.dish-image :deep(img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dish-info {
  flex: 1;
}

.dish-name {
  margin: 0 0 16px;
  font-size: 24px;
  font-weight: 500;
}

.dish-tags {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

.dish-price {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 16px;
}

.dish-description {
  color: #666;
  margin-bottom: 24px;
  line-height: 1.6;
}

.reviews-section {
  border-top: 1px solid #eee;
  padding-top: 24px;
}

.reviews-section h3 {
  margin: 0 0 16px;
  font-size: 18px;
  font-weight: 500;
}

.reviews-list {
  max-height: 400px;
  overflow-y: auto;
}

.reviews-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.reviews-summary {
  display: flex;
  align-items: center;
  gap: 12px;
}

.review-count {
  color: #666;
  font-size: 14px;
}

.review-item {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.reviewer-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.reviewer {
  font-weight: 500;
  color: #333;
}

.review-time {
  color: #999;
  font-size: 12px;
}

.review-content {
  color: #333;
  line-height: 1.6;
  margin-bottom: 12px;
}

.review-images {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.review-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
}

.review-reply {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  margin-top: 12px;
}

.reply-label {
  color: #666;
  font-weight: 500;
  margin-right: 8px;
}

.reply-content {
  color: #333;
}

.no-reviews {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 14px;
}

:deep(.el-rate) {
  display: inline-flex;
  align-items: center;
}

:deep(.el-rate__text) {
  font-size: 14px;
  color: #ff9900;
}
</style> 